//
//  HomeViewController.m
//  meiquan
//
//  Created by hejingjin on 2017/10/21.
//  Copyright © 2017年 mq. All rights reserved.
//

#import "HomeViewController.h"
#import "MQCollectionHeader.h"
#import "MQHomeProductCell.h"
#import "AdvertisementCollectionViewCell.h"
#import "CategoryCollectionViewCell.h"
#import "JHCollectionViewFlowLayout.h"
#import "MQSeallCenterViewController.h"
#import "MQMyStoreViewController.h"
#import "MQOrderManagerViewController.h"
#import "MQBaseUserInfoModel.h"
#import "MQpicProduct.h"
#import "MQAdmodel.h"
#import "MQProductListModel.h"
#import "MQCollectionHeader.h"

#import "MQProductViewController.h"
#import "MQSendProductViewController.h"

@interface HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,HJJCircleViewDelegate,JHCollectionViewDelegateFlowLayout>


@property(nonatomic,strong)UICollectionView *homepagecollectionview;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,strong)NSArray *titlearray;
@property(nonatomic,strong)NSArray *iconarray;
@property(nonatomic,strong)NSMutableArray *adarray;

@property(nonatomic,strong)NSMutableArray *admodelarray;


@end



@implementation HomeViewController
- (void)HJJCircleViewImageWithImageIndexFlag:(NSInteger)imageIndexFlag circleview:(HJJCircleView *)circleview{
    NSLog(@"%ld",imageIndexFlag);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.title = @"微商系统";
    
    [MQpicProduct mj_setupObjectClassInArray:^NSDictionary *{
        return @{
                 @"products" : @"MQProductListModel"
                 };
    }];
    
    _adarray = [NSMutableArray array];
    _admodelarray = [NSMutableArray array];
    _dataSource = [NSMutableArray array];
    
    _titlearray = @[@"智能硬件",@"购物车",@"买家中心",@"我的商城",@"扫一扫",@"订单管理",@"数据分析",@"帮助"];
    _iconarray = @[@"zhineng_yingjian",@"gouwuche",@"maijia_zhongx",@"wode_shangc",@"saoyisao",@"dinddan_guanl",@"shuju_fenx",@"bangzhu"];
//    _adarray = @[@"prodcdddd"];
    
    self.navigationItem.title = @"微商系统";
    
    [self setUpMainInterface];
    
    [self gethomeDate];
}



-(void)gethomeDate{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@"1" forKey:@"page"];
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    [param setValue:@"20" forKey:@"limit"];
    [param setValue:userinfo.userId forKey:@"userId"];
   
    
    [MQRequestTools POSTWithMethod:home_page params:param success:^(id json) {
        
        NSArray *banner = [[json valueForKey:@"data"] valueForKey:@"banner"];
        NSArray *picproduct = [[json valueForKey:@"data"] valueForKey:@"picProduct"];
        
        
        for (NSDictionary *dic in banner) {
            MQAdmodel *admodel = [MQAdmodel mj_objectWithKeyValues:dic];
            [_adarray addObject:admodel.pic];
            [_admodelarray addObject:admodel];
        }
        
        for (NSDictionary *dic in picproduct) {
            MQpicProduct *picmodel = [MQpicProduct mj_objectWithKeyValues:dic];
            [_dataSource addObject:picmodel];
        }
        
        [_homepagecollectionview reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
           return  [UICollectionReusableView new];
    }else{
   
        MQCollectionHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerviews" forIndexPath:indexPath];
        MQpicProduct *productmodel = _dataSource[indexPath.section - 2];
        
        [header.headerimageview sd_setImageWithURL:[NSURL URLWithString:productmodel.pic] placeholderImage:[UIImage imageNamed:@""]];
     
        header.tag = 10000 + indexPath.row;
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [header addGestureRecognizer:tapGesturRecognizer];
        
        
        return header;
    }
    
}
-(void)tapAction:(UITapGestureRecognizer *)objs{
    
    MQCollectionHeader *header =(MQCollectionHeader *)objs.view;
    
    NSInteger index = header.tag - 10000;
    MQpicProduct *productmodel = _dataSource[index];
    
    NSString *url =productmodel.url;
    NSLog(@"%@",url);
    
}

//返回头headerView的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    
    CGSize size;
    if (section == 0 || section == 1) {
        size = CGSizeMake(0, 0);
    }else{
        
        size = CGSizeMake(BSTScreenW, 100);
    }
    return size;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpMainInterface{
    
    self.view.backgroundColor = BSTColorFromRGB(0xefefef);
    
    [self.view addSubview:self.homepagecollectionview];
}

- (UIColor *)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout backgroundColorForSection:(NSInteger)section
{
    if (section < 2) {
        return [UIColor whiteColor];
    }else{
        return BSTColorFromRGB(0xefefef);
    }
}

-(UICollectionView *)homepagecollectionview{
    
    if (!_homepagecollectionview) {
        
        self.automaticallyAdjustsScrollViewInsets = NO;
        //
        
        
        JHCollectionViewFlowLayout *jhFlowLayout = [[JHCollectionViewFlowLayout alloc] init];
        jhFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        //初始化布局
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.minimumInteritemSpacing = 0;
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, BSTScreenW, BSTScreenH - NAVHEIGHT - TABBARHEIGHT) collectionViewLayout:jhFlowLayout];
        collectionView.backgroundColor = BSTColorFromRGB(0xefefef);
        
        _homepagecollectionview = collectionView;
        
        _homepagecollectionview.delegate = self;
        _homepagecollectionview.dataSource = self;
        //注册cell
        //1.轮播cell
//        [collectionView registerClass:[MQHomeProductCell class] forCellWithReuseIdentifier:@"homepagecellid"];
        
        //1.轮播cell
        [collectionView registerClass:[AdvertisementCollectionViewCell class] forCellWithReuseIdentifier:@"advercell"];
        
        
          [collectionView registerClass:[CategoryCollectionViewCell class] forCellWithReuseIdentifier:@"categorycell"];
        
        UINib *floorhomepagecellNib = [UINib   nibWithNibName:NSStringFromClass([MQHomeProductCell class]) bundle:[NSBundle mainBundle]];
        
        [collectionView registerNib:floorhomepagecellNib forCellWithReuseIdentifier:@"homepagecellid"];
        
        
        UINib *headererNib = [UINib   nibWithNibName:NSStringFromClass([MQCollectionHeader class]) bundle:[NSBundle mainBundle]];
        //
        [collectionView registerNib:headererNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerviews"];
    }
    return _homepagecollectionview;
}



-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        //广告位信息项目
        AdvertisementCollectionViewCell *adcell = [collectionView dequeueReusableCellWithReuseIdentifier:@"advercell" forIndexPath:indexPath];
        adcell.advercircleview.delegate = self;
        [adcell.advercircleview pauseTimer];
//        NSMutableArray *urlarray = [[NSMutableArray alloc] init];
//        if (_admodelarray.count > 0) {
//           MQAdmodel *admodel = _admodelarray[0];
//            adcell.advercircleview.datasource = [model.adList mutableCopy];
//            for (int i = 0; i < model.adList.count; i++) {
//                DSCQHomepageAdmodel *banner = model.adList[i];
//                NSString *urlstring = [BaseImageUrl stringByAppendingString:banner.imgUrl];
//                urlstring = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//                [urlarray addObject:urlstring];
//            }
//        }
//        if ([_admodelarray count] == 0) {
//            [adcell.advercircleview invalidateTimer];
//        }else{
//            adcell.advercircleview.imageDataarray = [urlarray mutableCopy];
//        }
        if (_adarray.count >0) {
           adcell.advercircleview.imageDataarray = [_adarray mutableCopy];  
        }
       
        return adcell;

    }else if(indexPath.section == 1){
        //分类
        CategoryCollectionViewCell *categorycell = [collectionView dequeueReusableCellWithReuseIdentifier:@"categorycell" forIndexPath:indexPath];
        categorycell.imageview.image = [UIImage imageNamed:_iconarray[indexPath.row]];
        categorycell.nameLabel.font = [UIFont systemFontOfSize:13];
        categorycell.nameLabel.text = _titlearray[indexPath.row];
        categorycell.nameLabel.textAlignment = NSTextAlignmentCenter;
        return categorycell;
    
    }else{
        MQHomeProductCell *categorycell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homepagecellid" forIndexPath:indexPath];
        MQpicProduct *picmodel = _dataSource[indexPath.section - 2];
        MQProductListModel *model = picmodel.products[indexPath.row];
        categorycell.productnameLabel.text = model.name;
        [categorycell.productcellimageview sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:plasces]];
        categorycell.productpricelabel.text = [NSString stringWithFormat:@"¥ %@",model.price];
        categorycell.propaycountlabel.text = [NSString stringWithFormat:@"%ld人付款",model.sales];
        return categorycell;
    }
    

    
}

//item 之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    CGFloat proportion = BSTScreenW/375;
    
    if(section == 1){
        return 20 * proportion;
    }else if(section == 0){
        return 0.f;
    }else{
        return 10 *proportion;
    }
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    CGFloat proportion = BSTScreenW/375;
    
    if(section == 1){
        return 25 * proportion;
    }else{
        return 0.f;
    }
    
}

//collectionview的Item大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size;
    
    CGFloat proportion = BSTScreenW/375;
    
    if (indexPath.section == 0) {
        size = CGSizeMake(BSTScreenW, 170 *proportion);
    }else if(indexPath.section == 1){
        size = CGSizeMake(46 * proportion, 65 * proportion);
    }else {
        size = CGSizeMake(184 *proportion, 251 * proportion);
    }
    return size;
}

//返回每一个sction中item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSInteger index;
    
    if (section == 0) {
        return 1;
    }else if(section ==1){
        return 8;
    }else{
        MQpicProduct *model = _dataSource[section - 2];
        return model.products.count;
    }
    
}

//section个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    //固定4个＋楼层个数
    return 2 + _dataSource.count;
    
}

//每一个section的间隔
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    CGFloat proportion = BSTScreenW/375;

       if(section == 0){
            return UIEdgeInsetsMake(0, 0, 10, 0);
        }else if(section == 1){
            return UIEdgeInsetsMake(10, 23.5 *proportion, 20, 23.5 *proportion);
        }else{
            return UIEdgeInsetsMake(10, 0 *proportion, 10,  0*proportion);
        }
    
    
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
//        CGFloat proportion = BSTScreenW/375;
//        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind :kind withReuseIdentifier:@"footerview" forIndexPath:indexPath];
//        NSArray *views = view.subviews;
//        for (id subview in views) {
//            [subview removeFromSuperview];
//        }
//        view.backgroundColor = BSTColorFromRGB(0xefeff4);
//        if (indexPath.section == _floorarray.count + 3) {
//            DSCQCustomFont *customfont = [DSCQCustomFont shareInstance];
//            UIButton *moreButton = [[UIButton alloc] initWithFrame:CGRectMake(24, 40, BSTScreenW - 48, 44)];
//            [moreButton setBackgroundColor:BSTColorFromRGB(0xfa5454)];
//            [moreButton setTitle:@"点击查看更多" forState:UIControlStateNormal];
//            [moreButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//            moreButton.titleLabel.font = [UIFont systemFontOfSize:18 + customfont.offsetFont];
//            [moreButton addTarget:self action:@selector(morebuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
//            moreButton.layer.cornerRadius = 5.f;
//            moreButton.layer.masksToBounds = YES;
//            [view addSubview:moreButton];
//        }
//        
//        NSMutableArray *numberarray = [NSMutableArray array];
//        
//        for (int i = 3; i< _floorarray.count + 3; i++) {
//            if (i%2==0) {
//                [numberarray addObject:@(i)];
//            }
//        }
//        if ([numberarray containsObject:@(indexPath.section)]) {
//            NSInteger dataindex = _adverarray.count - 1;
//            NSInteger index = (indexPath.section - 1 ) / 2;
//            if (index <= dataindex) {
//                DSCQHomePageNewsBannnerModel *bannermodel = _adverarray[index];
//                NSMutableArray *urlarray = [[NSMutableArray alloc] init];
//                for (int i = 0; i < bannermodel.adList.count; i++) {
//                    DSCQHomepageAdmodel *banner = bannermodel.adList[i];
//                    NSString *urlstring = [BaseImageUrl stringByAppendingString:banner.imgUrl];
//                    urlstring = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//                    [urlarray addObject:urlstring];
//                }
//                if (urlarray.count > 0) {
//                    HJJCircleView *cycleview = [[HJJCircleView alloc] initWithFrame:CGRectMake(0, 6*proportion, BSTScreenW, 86* proportion - 11 * proportion)];
//                    cycleview.datasource = [bannermodel.adList mutableCopy];
//                    cycleview.delegate = self;
//                    cycleview.imageDataarray = [urlarray mutableCopy];
//                    [view addSubview:cycleview];
//                }
//            }
//        }
//        return view;
//    }else{
//        
//        DSCQHomeTitleview *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerview" forIndexPath:indexPath];
//        
//        
//        DSCQFloorTitlesView *titleview = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerviews" forIndexPath:indexPath];
//        
//        if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2) {
//            return nil;
//        }else if(indexPath.section == _floorarray.count + 3){
//            titleview.hidden = YES;
//            view.titleNameLabel.text = @"竞价专场";
//            return view;
//        }else{
//            
//            DSCQHomePageFloorModel *homepagefloormodel = _floorarray[indexPath.section -3];
//            titleview.homepagefloormodel = homepagefloormodel;
//            [titleview.floormoreButton addTarget:self action:@selector(floormorebuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
//            view.hidden = YES;
//            titleview.hidden = NO;
//            return titleview;
//        }
//    }
//    
//}

//返回头headerView的大小
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    
//    
//    CGSize size;
//    if (section == 0 || section == 1 || section == 2) {
//        size = CGSizeMake(0, 0);
//    }else{
//        
//        size = CGSizeMake(BSTScreenW, 41);
//    }
//    return size;
//}
//
//返回footerView的大小
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    NSMutableArray *numberarray = [NSMutableArray array];
//    
//    //每2个之间 嵌套一个广告位
//    
//    for (int i = 3; i< _floorarray.count + 3; i++) {
//        if (i%2==0) {
//            [numberarray addObject:@(i)];
//        }
//    }
//    CGSize size;
//    CGFloat proportion = BSTScreenW/375;
//    if (section == 0) {
//        size = CGSizeMake(0, 0);
//    }else if(section == _floorarray.count +3){
//        size = CGSizeMake(BSTScreenW, 125 *proportion);
//    }else if ([numberarray containsObject:@(section)]){
//        //每2个配置的楼层中添加一个广告位 如果楼层没有配数据就不展示
//        NSInteger dataindex = _adverarray.count - 1;
//        NSInteger index = (section - 1 ) / 2;
//        if (index <= dataindex) {
//            DSCQHomePageNewsBannnerModel *bannermodel = _adverarray[index];
//            if (bannermodel.adList.count > 0) {
//                size = CGSizeMake(BSTScreenW, 86 * proportion);
//            }else{
//                size = CGSizeMake(BSTScreenW, 12);
//            }
//            
//        }else{
//            size = CGSizeMake(BSTScreenW, 12);
//        }
//        
//    }else{
//        size = CGSizeMake(BSTScreenW, 12);
//    }
//    return size;
//    
//}



//点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        switch (indexPath.row) {
            case 0:
                
                break;
            case 1:
                
                break;
            case 2:
                
                //买家中心
            {
                MQSeallCenterViewController *sealcentervc = [[MQSeallCenterViewController alloc] init];
                
                [self.navigationController pushViewController:sealcentervc animated:YES];
            }
                break;
            case 3:
                //我的商城
            {
                MQMyStoreViewController *mystorevc = [[MQMyStoreViewController alloc] init];
                [self.navigationController pushViewController:mystorevc animated:YES];
            }
          
                
                break;
            case 4:
                
                break;
            case 5:
            {
                MQOrderManagerViewController *ordermanagervc = [[MQOrderManagerViewController alloc] init];
                [self.navigationController pushViewController:ordermanagervc animated:YES];
            }
                break;
            case 6:
                
                break;
            case 7:
                
                break;
            default:
                break;
        }
        
    }else{
        MQpicProduct *picmodel = _dataSource[indexPath.section - 2];
        MQProductListModel *model = picmodel.products[indexPath.row];
        MQProductViewController *productvc = [[MQProductViewController alloc] init];
        productvc.model = model;
        [self.navigationController pushViewController:productvc animated:YES];
        
        
    }
    
}

@end
